package com.alisoft.nano.seda.test;

import java.util.Map;
import java.util.Random;

import com.alisoft.nano.seda.Event;
import com.alisoft.nano.seda.EventHandler;

public class SimpleEventHandler implements EventHandler<Map<String, String>> {

    private String nextStage = null;

    private Object R1 = new Object();
    private Object R2 = new Object();

    private Random random = new Random(System.currentTimeMillis());

    public void setNextStage(String nextStage) {
        this.nextStage = nextStage;
    }

    public void process(Event<Map<String, String>> event) {
        process1(event);
        process2(event);
    }

    public EventHandler<Map<String, String>> getEventHandler1() {
        return new EventHandler<Map<String, String>>() {

            public void process(Event<Map<String, String>> event) {
                process1(event);

            }

        };
    }

    public EventHandler<Map<String, String>> getEventHandler2() {
        return new EventHandler<Map<String, String>>() {

            public void process(Event<Map<String, String>> event) {
                process2(event);

            }

        };
    }

    protected void process2(Event<Map<String, String>> event) {
        try {

            double foo = 5.0;

            for (int i = 0; i < 1000000; i++) {
                foo = foo / 37.0;
            }

            Thread.sleep(random.nextInt(26));

            synchronized (R2) {
                for (int i = 0; i < 100; i++) {
                    foo = foo / 37.0;
                }
            }

            // Thread.sleep(130);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        event.setNextStage(nextStage);
    }

    protected void process1(Event<Map<String, String>> event) {
        event.getWorkUnit().put("result", "processed");
        System.out.println("Event handled in stage " + event.getCurrentStage());

        double foo = 5.0;
        synchronized (R1) {
            for (int i = 0; i < 100; i++) {
                foo = foo / 37.0;
            }
        }
        event.setNextStage(nextStage);
    }
}
